package com.lqq.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.lqq.commonutils.R;
import com.lqq.servicebase.exceptionHandler.GuliException;
import com.lqq.vod.service.VodService;
import com.lqq.vod.utils.ConstantPropertiesUtils;
import com.lqq.vod.utils.InitVodClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@Service
public class VodServiceImpl implements VodService {

    //上传视频到阿里云
    @Override
    public String uploadVideoAly(MultipartFile file) {
        String videoId = "";
        try {
            String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
            String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;

            String fileName = file.getOriginalFilename();
            String title = fileName.substring(0, fileName.lastIndexOf('.'));

            System.out.println(fileName);
            System.out.println(title);

            InputStream inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            if (response.isSuccess()) {
                videoId = response.getVideoId();
            } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                videoId = response.getVideoId();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            return videoId;
        }

    }


    //根据多个视频id删除阿里云的视频
    @Override
    public void removeMoreAlyVideo(List<String> videoList) {
        try {
            //初始化对象
            DefaultAcsClient client =
                    InitVodClient.initVodClient(ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.ACCESS_KEY_SECRET);
            //创建删除视频的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //将list转换成id1,id2,id3...形式
            String ids = StringUtils.join(videoList.toArray(), ",");
            //向request对象中设置视频id
            request.setVideoIds(ids);
            //调用初始化对象进行删除
            client.getAcsResponse(request);

        }catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "删除小节视频失败!");
        }
    }
}
